package com.jiang.demo.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jiang.demo.user.domain.User;
import com.jiang.demo.user.mapper.UserMapper;
import com.jiang.demo.user.service.UserServiceLogon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServicieLogonImpl implements UserServiceLogon {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Map<String, String> logon(Map<String, String> data) {
        String username = data.get("username");
        String password = data.get("password");
        String confirmedPassword = data.get("confirmedPassword");


        Map<String,String> map = new HashMap<>();
        if(username == null){
            map.put("error_message","用户名不能为空");
            return map;
        }
        if(password == null || confirmedPassword == null){
            map.put("error_message","密码不能为空");
            return map;
        }
        username = username.trim();
        password = password.trim();
        confirmedPassword = confirmedPassword.trim();

        if(username.length()==0){
            map.put("error_message","用户名不能为空");
            return map;
        }

        if(password.length()==0||confirmedPassword.length()==0){
            map.put("error_message","密码不能为空");
            return map;
        }

        if(username.length()>100){
            map.put("error_message","用户名长度不能大于100");
            return map;
        }
        if(password.length()>100||confirmedPassword.length()>100){
            map.put("error_message","密码长度不能大于100");
            return map;
        }
        if(!password.equals(confirmedPassword)){
            map.put("error_message","两次密码不一致");
            return map;
        }


        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        List<User> users = userMapper.selectList(queryWrapper);
        if(!users.isEmpty()){
            map.put("error_message","用户已存在");
            return map;
        }

        String encodedPassword = passwordEncoder.encode(password);//加密
        String photo = "https://img0.baidu.com/it/u=3663508195,2907650417&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500";


        User user = new User(
                null,
                encodedPassword,
                username,
                photo
        );
        userMapper.insert(user);
        map.put("error_message","success");
        return map;
    }
}
